package com.lxc.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lxc.entity.BusinessException;

import java.util.Calendar;
import java.util.Date;

public class Token {
    //生成token
    public static String generateToken(Long userId) throws Exception {
        Algorithm algorithm = Algorithm.RSA256(RSA.getPublicKey(), RSA.getPrivateKey());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());

        //第二个参数为自定义的常量Constant，token过期时间，为60*60=1小时
        calendar.add(Calendar.SECOND, 60*60);

        // 生成含userId的token,以后登录都只通过Header携带的token解析出userId进行业务
        return JWT.create().withKeyId(String.valueOf(userId))
                .withIssuer("com.lxc")
                .withExpiresAt(calendar.getTime())
                .sign(algorithm);
    }

    public static Long verifyToken(String token) {
        Algorithm algorithm = null;
        try {
            algorithm = Algorithm.RSA256(RSA.getPublicKey(), RSA.getPrivateKey());
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            String userId = jwt.getKeyId();
            return Long.valueOf(userId);
        } catch (TokenExpiredException e) {
            throw new BusinessException( 401,"token已过期！");
        } catch (Exception e) {
            throw new BusinessException(500, "token验证失败，请重试");
        }
    }

    public static String generateRefreshToken(Long userId) throws Exception {
        Algorithm algorithm = Algorithm.RSA256(RSA.getPublicKey(),RSA.getPrivateKey());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());

        // refreshToken的过期时间持续比较长，为60*60*24*7=7天
        calendar.add(Calendar.SECOND, 60*60*24*7);
        return JWT.create().withKeyId(String.valueOf(userId))
                .withIssuer("com.lxc")
                .withExpiresAt(calendar.getTime())
                .sign(algorithm);
    }

}
